﻿using System.Collections.Generic;
#if NETSTANDARD2_0
using Microsoft.AspNetCore.Http;
#endif
#if NET40 || NET45
using System.Web;
#endif
using Newtonsoft.Json;
using WeShare.WeiXin.Common;
using WeShare.WeiXin.Mp.TemplateNotice.Entity;
#if !NET40
using System.Threading.Tasks;
#endif
namespace WeShare.WeiXin.Mp.TemplateNotice
{
    /// <summary>
    /// /模板消息接口
    /// </summary>
    public static class TemplateNoticeApi
    {
        /// <summary>
        /// 设置公众号所属行业
        /// </summary>
        /// <param name="id1"></param>
        /// <param name="id2"></param>
        /// <param name="tokenOrAppId"></param>
        /// <returns></returns>
        public static BaseRes SetIndustry(string id1, string id2, string tokenOrAppId = "")
        {
            var url =
                $"https://api.weixin.qq.com/cgi-bin/template/api_set_industry?access_token={OpenApi.GetToken(tokenOrAppId)}";
            var json = new { industry_id1 = id1, industry_id2 = id2 };
            return HttpUtil.PostResult<BaseRes>(json, url);
        }
        /// <summary>
        /// 获取设置的行业信息
        /// </summary>
        /// <param name="tokenOrAppId"></param>
        /// <returns></returns>
        public static IndustryInfo GetIndustry(string tokenOrAppId = "")
        {
            var url =
                $"https://api.weixin.qq.com/cgi-bin/template/get_industry?access_token={OpenApi.GetToken(tokenOrAppId)}";
            return HttpUtil.GetResult<IndustryInfo>(url);
        }

        /// <summary>
        /// 获取模板ID
        /// </summary>
        /// <param name="templateNo">模板编号</param>
        /// <param name="tokenOrAppId"></param>
        public static TemplateID GeTemplateId(string templateNo, string tokenOrAppId = "")
        {
            var url =
                $"https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token={OpenApi.GetToken(tokenOrAppId)}";
            var json = new { template_id_short = templateNo };
            return HttpUtil.PostResult<TemplateID>(json, url);
        }

        /// <summary>
        /// 发送模板消息
        /// </summary>
        /// <param name="touser">要发送的用户的openid</param>
        /// <param name="templateId">模板ID</param>
        /// <param name="topcolor">消息卡片顶部的颜色</param>
        /// <param name="dataKeys">模板字段列表</param>
        /// <param name="url">点击消息卡片跳转的地址。默认为空。如果为空，ios设置会跳转到空白页面；安卓则不跳转</param>
        /// <param name="miniProgram"></param>
        /// <param name="tokenOrAppId"></param>
        /// <returns>调用成功后，返回的实体的msgid属性指的是此条模板消息的ID</returns>
        public static TemplateMsg Send(string touser, string templateId, string
        topcolor, Dictionary<string, TemplateKey> dataKeys,
         string url = "", MiniProgram miniProgram = null, string tokenOrAppId = "")
        {
            var turl =
                $"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={OpenApi.GetToken(tokenOrAppId)}";
            var json = new
            {
                touser = touser,
                template_id = templateId,
                url = url,
                topcolor = topcolor,
                miniprogram = miniProgram,
                data = dataKeys
            };
            return HttpUtil.PostResult<TemplateMsg>(json, turl);
        }
        /// <summary>
        /// 获取模板列表
        /// </summary>
        /// <returns></returns>
        public static Templates GetAllTemplate(string tokenOrAppId = "")
        {
            var url =
                $"https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token={OpenApi.GetToken(tokenOrAppId)}";
            return HttpUtil.GetResult<Templates>(url);
        }
        /// <summary>
        /// 删除模板
        /// </summary>
        /// <returns></returns>
        public static BaseRes DeleteTemplate(string tokenOrAppId = "")
        {
            var url =
                $"https://api.weixin.qq.com/cgi-bin/template/del_private_template?access_token={OpenApi.GetToken(tokenOrAppId)}";
            return HttpUtil.GetResult<BaseRes>(url);
        }
        /// <summary>
        /// 获取一次给用户推送一条订阅模板消息的机会。获取授权url
        /// </summary>
        /// <param name="scene">重定向后会带上scene参数，开发者可以填0-10000的整形值，用来标识订阅场景值</param>
        /// <param name="templateId">订阅消息模板ID，登录公众平台后台，在接口权限列表处可查看订阅模板ID</param>
        /// <param name="redirectUrl">授权后重定向的回调地址，请使用UrlEncode对链接进行处理。 注：要求redirect_url的域名要跟登记的业务域名一致，且业务域名不能带路径。 业务域名需登录公众号，在设置-公众号设置-功能设置里面对业务域名设置</param>
        /// <param name="reserved">用于保持请求和回调的状态，授权请后原样带回给第三方。该参数可用于防止csrf攻击（跨站请求伪造攻击），建议第三方带上该参数，可设置为简单的随机数加session进行校验，开发者可以填写a-zA-Z0-9的参数值，最多128字节，要求做urlencode</param>
        /// <param name="appid"></param>
        /// <returns></returns>
        public static string GetSubscribeMsgUrl(int scene, string templateId, string redirectUrl, string reserved = "",
            string appid = "")
        {
            if (string.IsNullOrEmpty(appid))
            {
                appid = OpenApi.GetConfig().AppId;
            }
            return $"https://mp.weixin.qq.com/mp/subscribemsg?action=get_confirm&appid={appid}&scene={scene}&template_id={templateId}&redirect_url={redirectUrl}&reserved={reserved}#wechat_redirect";
        }
        /// <summary>
        /// 获取订阅授权消息的回调参数
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static SubscribeCallBackParam GetSubscribeCallBackParam(this HttpContext context)
        {
            var openid = context.Request.QueryValue("openid");
            var templateId = context.Request.QueryValue("template_id");
            var action = context.Request.QueryValue("action");
            var scene = context.Request.QueryValue("scene");
            var reserved = context.Request.QueryValue("reserved");
            return new SubscribeCallBackParam
            {
                Action = action,
                OpenId = openid,
                TemplateId = templateId,
                Scene = scene,
                Reserved = reserved
            };
        }
        /// <summary>
        /// 推送订阅模板消息给到授权微信用户
        /// </summary>
        /// <param name="notice"></param>
        /// <param name="tokenOrAppId"></param>
        /// <returns></returns>
        public static BaseRes SendSubscribeMsg(SubscribeNotice notice, string tokenOrAppId = "")
        {
            var url = $"https://api.weixin.qq.com/cgi-bin/message/template/subscribe?access_token={OpenApi.GetToken(tokenOrAppId)}";
            return HttpUtil.PostResult<BaseRes>(notice,url);
        }

#if !NET40
        /// <summary>
        /// 设置公众号所属行业
        /// </summary>
        /// <param name="id1"></param>
        /// <param name="id2"></param>
        /// <param name="tokenOrAppId"></param>
        /// <returns></returns>
        public static async Task<BaseRes> SetIndustryAsync(string id1, string id2, string tokenOrAppId = "")
        {
            var url = $"https://api.weixin.qq.com/cgi-bin/template/api_set_industry?access_token={await OpenApi.GetTokenAsync(tokenOrAppId)}";
            var json = new { industry_id1 = id1, industry_id2 = id2 };
            return await HttpUtil.PostResultAsync<BaseRes>(json, url);
        }

        /// <summary>
        /// 获取模板ID
        /// </summary>
        /// <param name="templateNo">模板编号</param>
        /// <param name="accessToken">accessToken</param>
        /// <param name="tokenOrAppId"></param>
        public static async Task<TemplateID> GeTemplateIdAsync(string templateNo, string tokenOrAppId = "")
        {
            var url = $"https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token={await OpenApi.GetTokenAsync(tokenOrAppId)}";
            var json = new { template_id_short = templateNo };
            return await HttpUtil.PostResultAsync<TemplateID>(json, url);
        }

        /// <summary>
        /// 发送模板消息
        /// </summary>
        /// <param name="touser">要发送的用户的openid</param>
        /// <param name="templateId">模板ID</param>
        /// <param name="topcolor">消息卡片顶部的颜色</param>
        /// <param name="dataKeys">模板字段列表</param>
        /// <param name="url">点击消息卡片跳转的地址。默认为空。如果为空，ios设置会跳转到空白页面；安卓则不跳转</param>
        /// <param name="miniProgram"></param>
        /// <param name="tokenOrAppId"></param>
        /// <returns>调用成功后，返回的实体的msgid属性指的是此条模板消息的ID</returns>
        public static async Task<TemplateMsg> SendAsync(string touser, string templateId, string
        topcolor, Dictionary<string, TemplateKey> dataKeys,
         string url = "", MiniProgram miniProgram = null, string tokenOrAppId = "")
        {
            var turl = $"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={await OpenApi.GetTokenAsync(tokenOrAppId)}";
            var json = new
            {
                touser = touser,
                template_id = templateId,
                url = url,
                topcolor = topcolor,
                miniprogram = miniProgram,
                data = dataKeys
            };
            return await HttpUtil.PostResultAsync<TemplateMsg>(json, turl);
        }
        /// <summary>
        /// 获取模板列表
        /// </summary>
        /// <returns></returns>
        public static async Task<Templates> GetAllTemplateAsync(string tokenOrAppId = "")
        {
            var url = $"https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token={await OpenApi.GetTokenAsync(tokenOrAppId)}"; ;
            return await HttpUtil.GetResultAsync<Templates>(url);
        }
        /// <summary>
        /// 删除模板
        /// </summary>
        /// <returns></returns>
        public static async Task<BaseRes> DeleteTemplateAsync(string tokenOrAppId = "")
        {
            var url = $"https://api.weixin.qq.com/cgi-bin/template/del_private_template?access_token={await OpenApi.GetTokenAsync(tokenOrAppId)}";
            return await HttpUtil.GetResultAsync<BaseRes>(url);
        }
        /// <summary>
        /// 获取设置的行业信息
        /// </summary>
        /// <param name="tokenOrAppId"></param>
        /// <returns></returns>
        public static async Task<IndustryInfo> GetIndustryAsync(string tokenOrAppId = "")
        {
            var url =
                $"https://api.weixin.qq.com/cgi-bin/template/get_industry?access_token={OpenApi.GetToken(tokenOrAppId)}";
            return await HttpUtil.GetResultAsync<IndustryInfo>(url);
        }
        /// <summary>
        /// 推送订阅模板消息给到授权微信用户
        /// </summary>
        /// <param name="notice"></param>
        /// <param name="tokenOrAppId"></param>
        /// <returns></returns>
        public static async Task<BaseRes> SendSubscribeMsgAsync(SubscribeNotice notice, string tokenOrAppId = "")
        {
            var url = $"https://api.weixin.qq.com/cgi-bin/message/template/subscribe?access_token={await OpenApi.GetTokenAsync(tokenOrAppId)}";
            return await HttpUtil.PostResultAsync<BaseRes>(notice, url);
        }
#endif
    }
}
